package guiclient;

import client.Client;
import command.client.DisconnectConversationClient;
import command.client.SendMessageClient;
import java.awt.Color;
import java.util.ArrayList;
import java.util.Iterator;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import model.Conversation;
import model.Message;
import model.User;

public class GUIChatWindow extends javax.swing.JFrame {

    private Color colorBackgroud = new Color(240, 240, 240);
    private Client client;
    private Conversation conversation;
    private DefaultTableModel tableModel;
    private Message message = new Message();
    private GUIError error = new GUIError();

    public GUIChatWindow() {
        initComponents();
        getContentPane().setBackground(colorBackgroud);
        tableModel = (DefaultTableModel) membersJTable.getModel();
    }

    public GUIChatWindow(Client sessionOfClient, Conversation newConversation) {
        initComponents();
        getContentPane().setBackground(colorBackgroud);
        client = sessionOfClient;
        tableModel = (DefaultTableModel) membersJTable.getModel();
        setConversation(newConversation);
        setVisible(true);
    }

    public void setConversation(Conversation newConversation) {
        conversation = newConversation;
        updateUserChatList(conversation.getConversationUsersActive());
    }

    public Conversation getConversation() {
        return conversation;
    }

    public DefaultTableModel getMembersTableModel() {
        return tableModel;
    }

    public void setListOfMembers() {
        membersJTable = new JTable(tableModel);
    }

    public void updateUserChatList(ArrayList<User> userList) {
        if (userList.size() <= 1 && conversation.getConversationUsersActive().size() >= 2) {
            exitOfThisConversation();
        } else {
            conversation.setConversationUsersActive(userList);
            tableModel = (DefaultTableModel) membersJTable.getModel();
            tableModel.setNumRows(0);
            Iterator it = userList.iterator();
            while (it.hasNext()) {
                User u = (User) it.next();
                Object[] data = new Object[1];
                data[0] = u.getUserNickName();
                tableModel.addRow(data);
            }
            membersJTable.setModel(tableModel);
        }
    }

    public void addMessageToConversation(Message messageToAdd) {
        StringBuilder builderMessage = new StringBuilder();
        builderMessage.append(messageToAdd.getMessageDate());
        builderMessage.append(" - ");
        builderMessage.append(messageToAdd.getMessageUser().getUserNickName());
        builderMessage.append(" dijo: \n");
        builderMessage.append(messageToAdd.getMessageContent());
        builderMessage.append("\n");
        conversationJTextPane.setText(conversationJTextPane.getText() + builderMessage.toString());
    }

    private void sendMessage() {
        String messageContent = messageJTextField.getText();
        messageJTextField.setText("");
        message = new Message();
        message.setMessageContent(messageContent);
        message.setMessageUser(client.getSession().getUserSession());
        SendMessageClient command = new SendMessageClient();
        command.setConversationID(conversation.getConversationID());
        command.setMessage(message);
        command.execute(client.getSession(), false);
    }

    private void exitOfThisConversation() {
        DisconnectConversationClient command = new DisconnectConversationClient();
        command.setConversationID(conversation.getConversationID());
        command.execute(client.getSession(), false);
        client.getSession().getGUIChatPrincipal().getConversations().remove(
                this.conversation.getConversationID());
        this.dispose();
    }

    private void inviteOtherUserAtConversation() {
        ArrayList<String> usersInvite = new ArrayList<>();
        JTable usersActive = client.getSession().getGUIChatPrincipal().getUserListActiveJTable();
        int valueSelected = usersActive.getSelectedRow();
        DefaultTableModel model = client.getSession().getGUIChatPrincipal().getUserTableModel();
        String userNickName = client.getSession().getUserSession().getUserNickName();
        usersInvite.add((String) model.getValueAt(valueSelected, 0));
        if (usersInvite.contains(userNickName)) {
            usersInvite.remove(userNickName);
        }
        if (usersInvite.size() > 0) {
            client.inviteUsersAtConversation(usersInvite, userNickName, conversation);
        } else {
            error.setErrorMessage("Forever Alone...");
            error.setVisible(true);
        }
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jEditorPane1 = new javax.swing.JEditorPane();
        inviteChatJButton = new javax.swing.JButton();
        exitChatJButton = new javax.swing.JButton();
        firstSeparator = new javax.swing.JSeparator();
        conversationJScrollPane = new javax.swing.JScrollPane();
        conversationJTextPane = new javax.swing.JTextPane();
        thirdSeparator = new javax.swing.JSeparator();
        conversationJLabel = new javax.swing.JLabel();
        messageJLabel = new javax.swing.JLabel();
        fourthSeparator = new javax.swing.JSeparator();
        infoJLabel = new javax.swing.JLabel();
        messageJButton = new javax.swing.JButton();
        secondSeparator = new javax.swing.JSeparator();
        membersJScrollPane = new javax.swing.JScrollPane();
        membersJTable = new javax.swing.JTable();
        messageJTextField = new javax.swing.JTextField();
        chatWindowJMenuBar = new javax.swing.JMenuBar();
        optionsChatWindowJMenu = new javax.swing.JMenu();
        inviteChatJMenuItem = new javax.swing.JMenuItem();
        exitChatJMenuItem = new javax.swing.JMenuItem();

        jScrollPane1.setViewportView(jEditorPane1);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Conversación");
        setLocationByPlatform(true);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        inviteChatJButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/guiclient/images/inviteuser60.png"))); // NOI18N
        inviteChatJButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        inviteChatJButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                inviteChatJButtonActionPerformed(evt);
            }
        });

        exitChatJButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/guiclient/images/ExitConversation60.png"))); // NOI18N
        exitChatJButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        exitChatJButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitChatJButtonActionPerformed(evt);
            }
        });

        conversationJTextPane.setEditable(false);
        conversationJScrollPane.setViewportView(conversationJTextPane);

        conversationJLabel.setText("Conversación:");

        messageJLabel.setText("Mensaje:");

        messageJButton.setText("Enviar");
        messageJButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                messageJButtonActionPerformed(evt);
            }
        });

        secondSeparator.setOrientation(javax.swing.SwingConstants.VERTICAL);

        membersJTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Participantes"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        membersJScrollPane.setViewportView(membersJTable);

        messageJTextField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                messageJTextFieldKeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                messageJTextFieldKeyReleased(evt);
            }
        });

        optionsChatWindowJMenu.setText("Opciones");

        inviteChatJMenuItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/guiclient/images/inviteuser30.png"))); // NOI18N
        inviteChatJMenuItem.setText("Invitar a otro usuario");
        inviteChatJMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                inviteChatJMenuItemActionPerformed(evt);
            }
        });
        optionsChatWindowJMenu.add(inviteChatJMenuItem);

        exitChatJMenuItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/guiclient/images/ExitConversation30.png"))); // NOI18N
        exitChatJMenuItem.setText("Abandonar la Conversación");
        exitChatJMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitChatJMenuItemActionPerformed(evt);
            }
        });
        optionsChatWindowJMenu.add(exitChatJMenuItem);

        chatWindowJMenuBar.add(optionsChatWindowJMenu);

        setJMenuBar(chatWindowJMenuBar);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(firstSeparator, javax.swing.GroupLayout.Alignment.TRAILING)
            .addComponent(fourthSeparator, javax.swing.GroupLayout.Alignment.TRAILING)
            .addComponent(thirdSeparator)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(infoJLabel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(messageJTextField)
                        .addGap(18, 18, 18)
                        .addComponent(messageJButton, javax.swing.GroupLayout.PREFERRED_SIZE, 154, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(conversationJLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 309, Short.MAX_VALUE)
                            .addComponent(conversationJScrollPane))
                        .addGap(16, 16, 16)
                        .addComponent(secondSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(membersJScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(messageJLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(inviteChatJButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(exitChatJButton)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(exitChatJButton)
                    .addComponent(inviteChatJButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(firstSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 5, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(6, 6, 6)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(secondSeparator)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(conversationJLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(conversationJScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 202, Short.MAX_VALUE))
                    .addComponent(membersJScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 11, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(thirdSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 8, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(messageJLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(messageJTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(messageJButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(fourthSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 5, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(infoJLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
    }//GEN-LAST:event_formWindowClosed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        exitOfThisConversation();
    }//GEN-LAST:event_formWindowClosing

    private void inviteChatJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_inviteChatJButtonActionPerformed
        inviteOtherUserAtConversation();
    }//GEN-LAST:event_inviteChatJButtonActionPerformed

    private void exitChatJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitChatJButtonActionPerformed
        exitOfThisConversation();
    }//GEN-LAST:event_exitChatJButtonActionPerformed

    private void messageJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_messageJButtonActionPerformed
        sendMessage();
    }//GEN-LAST:event_messageJButtonActionPerformed

    private void messageJTextFieldKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_messageJTextFieldKeyPressed
    }//GEN-LAST:event_messageJTextFieldKeyPressed

    private void messageJTextFieldKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_messageJTextFieldKeyReleased
        if (evt.getKeyCode() == 10) {
            sendMessage();
        }
    }//GEN-LAST:event_messageJTextFieldKeyReleased

    private void exitChatJMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitChatJMenuItemActionPerformed
        exitOfThisConversation();
    }//GEN-LAST:event_exitChatJMenuItemActionPerformed

    private void inviteChatJMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_inviteChatJMenuItemActionPerformed
        inviteOtherUserAtConversation();
    }//GEN-LAST:event_inviteChatJMenuItemActionPerformed

    public static void main(String args[]) {
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException |
                javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(GUIChatWindow.class.getName()).log(java.util.logging.Level.SEVERE,
                    "Fallo al inicializar la ventana de una conversación", ex);
        }
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new GUIChatWindow().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuBar chatWindowJMenuBar;
    private javax.swing.JLabel conversationJLabel;
    private javax.swing.JScrollPane conversationJScrollPane;
    private javax.swing.JTextPane conversationJTextPane;
    private javax.swing.JButton exitChatJButton;
    private javax.swing.JMenuItem exitChatJMenuItem;
    private javax.swing.JSeparator firstSeparator;
    private javax.swing.JSeparator fourthSeparator;
    private javax.swing.JLabel infoJLabel;
    private javax.swing.JButton inviteChatJButton;
    private javax.swing.JMenuItem inviteChatJMenuItem;
    private javax.swing.JEditorPane jEditorPane1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane membersJScrollPane;
    private javax.swing.JTable membersJTable;
    private javax.swing.JButton messageJButton;
    private javax.swing.JLabel messageJLabel;
    private javax.swing.JTextField messageJTextField;
    private javax.swing.JMenu optionsChatWindowJMenu;
    private javax.swing.JSeparator secondSeparator;
    private javax.swing.JSeparator thirdSeparator;
    // End of variables declaration//GEN-END:variables
}
